import React, { Component } from 'react';
import "./cart.css"
import { NavBar, Icon ,Modal} from 'antd-mobile';
import Img4 from "../../assets/images/gouwuc.jpg"
const alert = Modal.alert;
class cart extends Component {
    constructor(props){
        super(props)
        // this.ADD = React.createRef()
       
    }
    state = {
        carts: [],
        allChecked: true,
        totalPrice:0,
        allNum:0,
        token:[],
        num1:3
        
    }
    componentDidMount() {
        //获取token值
        let token_str = localStorage.getItem("token")
        let token = JSON.parse(token_str)
        this.setState({
            token
        })
        let cart_str = localStorage.getItem("carts")
        let carts = JSON.parse(cart_str || "[]")
        //判断状态
        let allChecked = true
        
        carts.some(v => {
            if (!v.checked) {
                allChecked = false
            }
        })
        // this.ADD.current.parentElement.addEventListener('mousedown',)
        this.setState({
            allChecked
        })
        this.saveCarts(carts)
        let timer
        if(!token){
            timer =setInterval(()=>{
               let num1 = this.state.num1
               this.setState({
                    num1:num1 - 1
               })
               if(num1==0){
                clearInterval(timer)
                this.props.history.push("login")
                
               }
               
           },1000) 
        }
        
    }
    
    // onTouchStart(){
    //     this.timeOutEvent = setTimeout(function() {
    //     this.timeOutEvent = 0;
    //     this.handleAdd()
    //     }, 400);}
    //保存
    saveCarts = (carts) => {
        this.carts = carts
        localStorage.setItem("carts", JSON.stringify(carts))
        this.setState({
            carts
        })
        this.comTotalPrice()
        this.allNum()
    }
    // //选中
    handleSelect =(index) => {
        let carts = this.state.carts
        carts[index].checked = !carts[index].checked
        let bool = carts.some(v => {
            if (!v.checked) {
                return true
            }
        })
        if (bool) {
            this.setState({
                allChecked: false
            })
        } else {
            this.setState({
                allChecked: true
            })
        }
        this.saveCarts(carts)
    }
    //全选按钮
    handleAllCheck = (params) => {
        let allChecked = !this.state.allChecked
        this.carts.forEach(v => {
            v.checked = allChecked
        })
        // this.saveCarts(this.carts)
        this.saveCarts(this.carts)
        this.setState({
            allChecked
        })
    }
    // //加
    onTouch =(index) => {
        
        let carts = this.state.carts
        carts[index].num++
        carts[index].checked = true
        // this.onTouchStart()
        let bool = carts.some(v => {
            if (!v.checked) {
                return true
            }
        })
        if (bool) {
            this.setState({
                allChecked: false
            })
        } else {
            this.setState({
                allChecked: true
            })
        }
       this.saveCarts(carts)
        
    }
    handleMove =(params) => {
       
    }
    //减
    handleSub =(index) => {
        let carts = this.state.carts
        if(carts[index].num - 1 === 0){
            alert('删除', '你确定嘛', [
                { text: '取消', onPress: () => console.log('cancel') },
                {
                    text: '确定', onPress: () => {
                        carts.splice(index, 1)
                        this.saveCarts(carts)
                       
                    }
                },
            ])
        }else{
            carts[index].num--
            this.saveCarts(carts)
        }
    }
    //删除
    handleDelete = (index) => {
        let carts = this.state.carts
        alert('删除', '你确定嘛', [
            { text: '再想想', onPress: () => console.log('cancel') },
            {
                text: '确定', onPress: () => {
                    carts.splice(index, 1)
                    this.saveCarts(carts)
                   
                }
            },
        ])
        // carts.splice(index,1)
        // this.saveCarts(carts)
    }
     //计算总价
     comTotalPrice =(params) => {
        let totalPrice = 0 
        this.carts.forEach(v=>{
            if(v.checked){
               totalPrice += v.price * v.num
            }
        }) 
        this.setState({
           totalPrice
        })
   }
   //勾选总数量
   allNum =(params) => {
    let allNum = 0
    this.carts.forEach(v=>{
        if(v.checked){
            allNum += v.num
        }
    })
    this.setState({
        allNum
    })
}
handleToPay =(params) => {
    
    let carts_str = localStorage.getItem("carts")
    let carts = JSON.parse(carts_str)
    let buyNow = []
    carts.forEach(val=>{
        if(val.checked){
            buyNow.push(val)
        }
    })
    localStorage.setItem("buyNow",JSON.stringify(buyNow))
    this.props.history.push("pay")
}
handleToLogin =(params) => {
    this.props.history.push("login")
}
    render() {
        return (
            
            this.state.token?<div className="jx-cart-content">
                {
                    !!this.state.carts.length?<div className="jx-cart-header">
                        <NavBar
                            className="cart-text"
                            mode="light"
                            icon={<Icon type="left" />}
                            onLeftClick={() => window.history.go(-1)}
                            rightContent={[
                                <Icon key="1" type="ellipsis" />,
                            ]}
                        >购物车</NavBar>
                    
                    {/* 导航的结束 */}
                    <div className="cart-jg-nav">
                        <i className="jg-title"><span>!</span></i>
                        <div className="title">自营商品满付满100元免运费，偏远地区满500元免运费</div>
                    </div>
                    {/* 购物车部分开始 */}
                    <div className="cart-content">
                        {
                            this.state.carts.map((v, i) => {
                                return <div className="cart" key={v.id}>
                                    <div className="content-item-left" onClick={this.handleSelect.bind(this, i)}>
                                    <i className={v.checked ? "select_circle" : "content-wrap"}></i>
                                        
                                    </div>
                                    <div className="content-item-mid">
                                        <img src={v.imgList} alt="" />
                                    </div>
                                    <div className="content-item-right">
                                        <div className="right-top">
                                            {v.name}
                                        </div>
                                        <span className="price">￥{v.price}</span>
                                        <div className="right-bottom">
                                            <div className="bottom-left">
                                                <div className="sub" onClick={this.handleSub.bind(this, i)}>-</div>
                            <div className="num">{v.num}</div>
                                                <div className="add" onTouchStart={this.onTouch.bind(this, i)}>+</div>
                                            </div>
                                            <div className="bottom-right" onClick={this.handleDelete.bind(this,i)}>
                                                |&nbsp;<span>删除</span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            })
                        }
                    </div>
                    {/* 购物车部分结束 */}              
                    {/* 底部支付的开始 */}
                    <div className="cart-content-bottom">
                        <div className="all-checked" onClick={this.handleAllCheck}>
                            <i className={this.state.allChecked?"select_all":"selectALL"}></i>
                            <span className="test">全选</span>
                        </div>
                        <div className="totalPrice">
                            <div className="box1">
                                <span className="text1">合计</span>
                    <span className="price">￥{this.state.totalPrice}</span>
                            </div>
                            <div className="box2">
                                <span className="text2">优惠</span>
                                <span className="price">￥0.00</span>
                            </div>
                        </div>
                        <div className="pay">
                            {
                                !this.state.allNum?<div className="text5">去结算({this.state.allNum})</div>: <div className="text3" onClick={this.handleToPay}>去结算({this.state.allNum})</div>
                            }
                        </div>
                    </div>
                    {/* 底部支付的结束 */}
                </div>:<div className="yg-cart-img">
                            <img src={Img4} alt="" className="cart-ig" />
                            <h3 className="title"><a href="#/category">空空如也，去逛逛吧！！</a></h3>
                        </div>
                }
            </div>:<div className="To-login">
                 <h1 onClick={this.handleToLogin}>请先登入,才能看我！</h1>
            <h2>{this.state.num1}</h2>
            </div>
        
        );
    }
}

export default cart;